<script lang="ts" setup>
import { onMounted, ref } from 'vue';
import { useRouter } from 'vue-router';
import { listForm, listFormRemove } from '@/api/workflow/form';
import FormRender from '../components/FormRender.vue';
import { ElMessage, ElMessageBox } from 'element-plus';

const router = useRouter();
const list = ref([]);

onMounted(() => {
  getData();
});

async function getData() {
  try {
    const { rows } = await listForm();
    list.value = rows;
  } catch (error) {
    console.log(error);
  }
}

function toDetail(item) {
  router.push({ name: 'form-detail', query: { formId: item.formId } });
}

const formOpen = ref(false);
const formTitle = ref('');
const formJson = ref('');
const formData = ref({
  input56354: '123',
  radio103140: 1,
  select32879: 1,
  daterange71446: ['2025-09-05', '2025-09-23'],
  switch104110: true
});

function toViewer(item) {
  formTitle.value = item.formName;
  formJson.value = item.content;
  console.log(JSON.parse(item.content).widgetList);
  formOpen.value = true;
}

function onRemove(item) {
  ElMessageBox.confirm('确定要删除吗？', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(async () => {
    try {
      await listFormRemove(item.formId);
      ElMessage.success('删除成功');
      await getData();
    } catch (error) {
      ElMessage.error(error.message);
    }
  });
}

const formRenderRef = ref(null);
async function onSubmit() {
  try {
    const data = await formRenderRef.value.getFormData();
    console.log(data);
    ElMessage.success('提交成功');
  } catch (error) {
    console.log(error);
  }
}
</script>

<template>
  <el-row>
    <el-col>
      <el-button plain size="large" type="primary" @click="toDetail('add')">新增</el-button>
    </el-col>
  </el-row>
  <br />
  <el-table :data="list" height="calc(100% - 100px)">
    <el-table-column label="序号" width="200">
      <template #default="scope">
        {{ scope.$index + 1 }}
      </template>
    </el-table-column>
    <el-table-column label="表单ID" prop="formId" show-overflow-tooltip />
    <el-table-column label="表单名称" prop="formName" show-overflow-tooltip />
    <el-table-column label="操作" width="200">
      <template #default="scope">
        <el-button link type="primary" @click="toViewer(scope.row)">预览</el-button>
        <el-button link type="primary" @click="toDetail(scope.row)">编辑</el-button>
        <el-button link type="danger" @click="onRemove(scope.row)">删除</el-button>
      </template>
    </el-table-column>
  </el-table>

  <!-- 预览 -->
  <el-dialog v-model="formOpen" :title="formTitle" append-to-body width="500px">
    <form-render ref="formRenderRef" :data="formData" :is-disable="false" :json="formJson"></form-render>
    <template #footer>
      <el-button @click="formOpen = false">取消</el-button>
      <el-button type="primary" @click="onSubmit">提交</el-button>
    </template>
  </el-dialog>
</template>

<style lang="scss" scoped></style>
